package com.artisan.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.artisan.model.Admin;
import com.artisan.model.SelectedCourse;
import com.artisan.model.Student;

public class AdminDao extends BaseDao {
	/*
	 * 管理员登录
	 */
	public Admin login(Admin admin) {
		String sql = "select * from s_admin where name = ? and password = ?";
		Admin adminRet = null;
		try {
			PreparedStatement prst = con.prepareStatement(sql); // 把sql语句传给数据库操作对象
			prst.setString(1, admin.getName());
			prst.setString(2, admin.getPassword());
			ResultSet executeQurey = prst.executeQuery();
			if (executeQurey.next()) {
				adminRet = new Admin();
				adminRet.setId(executeQurey.getInt("id"));
				adminRet.setName(executeQurey.getString("name"));
				adminRet.setPassword(executeQurey.getString("password"));
				adminRet.setCreateDate(executeQurey.getString("createDate"));
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return adminRet;
	}

	public String editPassword(Admin admin, String newPassword) {
		String sql = "select * from s_admin where id = ? and password = ?";
		PreparedStatement prst = null;
		int id = 0;
		try {
			prst = con.prepareStatement(sql);
			prst.setInt(1, admin.getId());
			prst.setString(2, admin.getPassword());
			ResultSet executeQurey = prst.executeQuery();
			if (!executeQurey.next()) {
				String retString = "旧密码错误!";
				return retString;
			}
			id = executeQurey.getInt("id");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		String retString = "修改失败!";
		String sqlString = "update s_admin set password = ? where id = ? ";
		try {
			prst = con.prepareStatement(sqlString);
			prst.setString(1, newPassword);
			prst.setInt(2, id);
			int ret = prst.executeUpdate();
			if (ret > 0) {
				retString = "密码修改成功!";
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} // 把sql语句传给数据库操作对象
		return retString;
	}

	public boolean enrollAdmin(Admin admin) {
		String sql = "insert into s_admin values(null,?,?,?) ";
		try {
			PreparedStatement preparedStatement = con.prepareStatement(sql);
			preparedStatement.setString(1, admin.getName());
			preparedStatement.setString(2, admin.getPassword());
			preparedStatement.setString(3, admin.getCreateDate());
			if (preparedStatement.executeUpdate() > 0) {
				return true;
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return false;
	}

	public boolean isAdminSelected(Admin admin) {
		String sql = "select * from s_admin where name = ? ";
		try {
			PreparedStatement prst = con.prepareStatement(sql);// 把sql语句传给数据库操作对象
			prst.setString(1, admin.getName());
			ResultSet executeQuery = prst.executeQuery();
			if (executeQuery.next()) {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
